package org.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.stereotype.Component;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import lombok.extern.slf4j.Slf4j;

@SpringBootApplication
@EntityScan(basePackages = "org.example.model")
@EnableJpaRepositories(basePackages = "org.example.repository")
@MapperScan("org.example.mapper")
@EnableTransactionManagement //开启事务注解
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
    
    /**
     * 启动时初始化必要的目录
     */
    @Component
    @Slf4j
    static class DirectoryInitializer implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            // 确保文章图片目录存在
            createDirectoryIfNotExists("static/image/article");
            createDirectoryIfNotExists("image/article");
            
            // 确保问卷图片目录存在
            createDirectoryIfNotExists("static/image/question");
            createDirectoryIfNotExists("image/question");
        }
        
        private void createDirectoryIfNotExists(String path) {
            File directory = new File(path);
            if (!directory.exists()) {
                boolean created = directory.mkdirs();
                if (created) {
                    log.info("目录已创建: {}", directory.getAbsolutePath());
                } else {
                    log.warn("无法创建目录: {}", directory.getAbsolutePath());
                }
            } else {
                log.info("目录已存在: {}", directory.getAbsolutePath());
            }
        }
    }
}
